<template>
  <BasicModal
    v-bind="$attrs"
    :title="
      modalType == 'share'
        ? t('routes.demo.documentManager.operationButton.share')
        : t('routes.demo.documentManager.operationButton.publish')
    "
    @register="register"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :minHeight="450"
    :width="1000"
  >
    <!-- 表单填写发布人以及截止时间 -->
    <BasicForm @register="registerForm" />
    <!-- 表格填写发布文档内容 -->
    <BasicTable @register="registerRelTable" />
  </BasicModal>
  <!-- 发布流程 -->
  <initiateFlowCopy @register="registerModalCopy" />
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { AddRelForm, getRelColumns } from './tableData';
  import { AddEditingRecord } from '/@/api/demo/document';
  import { WriteDownPublishsFiles } from '/@/api/demo/flow';
  import { Getallpersondto } from '/@/api/demo/system';
  import { useMessage } from '/@/hooks/web/useMessage';

  // 引入发起流程弹窗
  import initiateFlowCopy from '/@/views/demo/workFlow/initiateFlowCopy.vue';

  const { createMessage } = useMessage();
  const emit = defineEmits(['register', 'cancelRelation']);
  const { t } = useI18n();
  // 发布类型
  const relType = ref('');
  // 判断模态框类型，share为分享，publish为发布
  const modalType = ref('');

  // 提交
  const handleSubmit = async () => {
    const data = await validate();
    setModalProps({ confirmLoading: true });
    if (modalType.value == 'share') {
      const params = {
        docIds: getDataSource().map((item) => item.oId),
        editUserIds: data.userOrRoleIds,
        editStartTime: data.startTime,
        editEndTime: data.deadline,
        founder: getDataSource().map((item) => item.checkOutPerson)[0],
      };
      const res = await AddEditingRecord(params);
      if (res) {
        createMessage.success('共享成功');
        handleCancel();
      }
    } else if (modalType.value == 'publish') {
      const params = {
        userOrRoleIds: data.userOrRoleIds,
        deadLine: data.deadline,
        startTime: data.startTime,
        writeDownDocData: getDataSource().map((item) => {
          return {
            oid: item.oId,
            version: item.version,
            docName: item.filename,
          };
        }),
      };
      WriteDownPublishsFiles(params).then((res) => {
        if (res) {
          if (relType.value === '批量') {
            let selectedFiles = getDataSource();
            if (selectedFiles.length == 1) {
              openModalCopy(true, {
                record: selectedFiles[0],
                type: '发布流程',
                selectedFiles: '',
                projectid: '',
                projectName: '',
                taskName: '',
                formId: '',
                state: '图档',
                isUpdate: false,
                ReleaseProcessID: res,
              });
            } else {
              openModalCopy(true, {
                record: '',
                type: '发布流程',
                selectedFiles: selectedFiles,
                projectid: '',
                projectName: '',
                taskName: '',
                formId: '',
                state: '图档',
                isUpdate: false,
                ReleaseProcessID: res,
              });
            }
          } else {
            let selectedFiles = getDataSource();
            openModalCopy(true, {
              record: selectedFiles[0],
              type: '发布流程',
              selectedFiles: '',
              projectid: '',
              projectName: '',
              taskName: '',
              formId: '',
              state: '图档',
              isUpdate: false,
              ReleaseProcessID: res,
            });
          }
          handleCancel();
        }
      });
    }
  };
  // 取消
  const handleCancel = () => {
    setModalProps({ confirmLoading: false });
    emit('cancelRelation');
    closeModal();
  };
  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    setTableData(data.relList);
    relType.value = data.relType;
    modalType.value = data.modalType;
    Getallpersondto({}).then((res) => {
      const newData = res.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
      updateSchema({
        field: 'userOrRoleIds',
        componentProps: {
          options: newData,
        },
      });
    });
  });
  // 发布人以及截止时间
  const [registerForm, { validate, updateSchema }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
    schemas: AddRelForm(),
    showResetButton: false,
    showSubmitButton: false,
  });
  // 发布文档内容
  const [registerRelTable, { setTableData, getDataSource }] = useTable({
    columns: getRelColumns(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: false, // 显示表格设置工具
    tableSetting: { fullScreen: false }, // 表格设置工具配置
    canResize: false,
  });

  const [registerModalCopy, { openModal: openModalCopy }] = useModal();
</script>

<style lang="less" scoped>
  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }
</style>
